package cn.clx.ymcc.consumer;

import cn.clx.ymcc.domain.CourseMarket;
import cn.clx.ymcc.domain.CourseUserLearn;
import cn.clx.ymcc.dto.PayNotifyDto;
import cn.clx.ymcc.service.ICourseMarketService;
import cn.clx.ymcc.service.ICourseUserLearnService;
import cn.clx.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 *  pay微服务，成功支付，消费消息添加learn表的权限
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "pay-success-topic",
        selectorExpression="course-order-saveorupdate-tags"	//tags
                ,consumerGroup = "service-pay-to-course-consumer",
        messageModel = MessageModel.BROADCASTING)
public class CourseLearnSaveMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseUserLearnService courseUserLearnService;
    @Autowired
    private ICourseMarketService courseMarketService;

    /**
     * 需保证消费的幂等性
     * @param message
     */
    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        log.info("执行支付宝异步回调，mq消息修改courseLearn表状态");
        String msg = new String(message.getBody(), CharsetUtil.UTF_8);
        if(msg==null){
            return;  //为空签收
        }
        PayNotifyDto payNotifyDto = JSONObject.parseObject(msg, PayNotifyDto.class);
        String extParams = payNotifyDto.getExtParams();
        String[] split = extParams.split(":");
        String userid = split[0];
        String courseId = split[1];
        String[] courseids = courseId.split(",");
        Date date = new Date();
        for (String courseid : courseids) {
            Wrapper<CourseUserLearn> wrapper=new EntityWrapper<>();
            wrapper.eq("login_id",userid);
            wrapper.eq("course_id",courseid);
            CourseMarket courseMarket = courseMarketService.selectById(courseid);
            CourseUserLearn coursepermission =courseUserLearnService.selectOne(wrapper);
            if(coursepermission==null){
                //查不到
                CourseUserLearn courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(Long.valueOf(courseid));
                courseUserLearn.setCourseOrderNo(payNotifyDto.getOrderNo());
                courseUserLearn.setLoginId(Long.valueOf(userid));
                courseUserLearn.setState(CourseUserLearn.STATE_OK);
                courseUserLearn.setCreateTime(date);
                courseUserLearn.setStartTime(date);
                courseUserLearn.setEndTime(DateUtils.addDays(date,courseMarket.getValidDays()));
                courseUserLearnService.insert(courseUserLearn);
            }else {//查得到
                coursepermission.setCourseOrderNo(payNotifyDto.getOrderNo());
                //课程未过期，续费时间
                if(coursepermission.getState()==CourseUserLearn.STATE_OK && coursepermission.getEndTime().before(date)){
                    coursepermission.setState(CourseUserLearn.STATE_OK);
                    coursepermission.setStartTime(date);
                    coursepermission.setEndTime(DateUtils.addDays(date,courseMarket.getValidDays()));
                    courseUserLearnService.updateById(coursepermission);
                }else {
                    //查得到，，续费，增加时间
                    coursepermission.setState(CourseUserLearn.STATE_OK);
                    coursepermission.setStartTime(date);
                    Date date1 = DateUtils.addDays(coursepermission.getEndTime(), courseMarket.getValidDays());
                    coursepermission.setEndTime(date1);
                    courseUserLearnService.updateById(coursepermission);
                }
            }


        }
    }
}